package com.cl.blog.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cl.blog.entity.BAdmin;
import com.cl.blog.entity.BUser;
import com.cl.blog.exception.WebException;
import com.cl.blog.mapper.BUserMapper;
import com.cl.blog.service.BAdminService;
import com.cl.blog.mapper.BAdminMapper;
import com.cl.blog.service.BUserService;
import com.cl.blog.util.RedisUtil;
import com.cl.blog.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author object
 * @description 针对表【b_admin】的数据库操作Service实现
 * @createDate 2024-03-14 17:13:59
 */
@Service
public class BAdminServiceImpl extends ServiceImpl<BAdminMapper, BAdmin>
		implements BAdminService {

	@Autowired
	RedisUtil redisUtil;
	@Autowired
	BUserMapper bUserMapper;

	@Override
	public BAdmin login(LoginVo loginVo) {
		Object code = redisUtil.get(loginVo.getUuid());
		System.out.println(code + "-" + (loginVo.getCode().equals(code.toString())) + "-" + (loginVo.getCode().equals(code)));
		if (!loginVo.getCode().equals(code)) {
			throw new WebException("抱歉，验证码错误");

		}
		BAdmin bAdmin = this.getOne(new QueryWrapper<BAdmin>().eq("username", loginVo.getUsername()));

		Assert.notNull(bAdmin, "抱歉，用户名或密码错误");
		Assert.isTrue(bAdmin.getPassword().equals(SecureUtil.md5(loginVo.getPassword())), "抱歉，用户名或密码错误");

		return bAdmin;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean authorization(Integer userId, Integer roleId) {
		// 先查询该用户是否已经有权限了
		BAdmin bAdmin = this.getById(userId);
		if (bAdmin!=null){
			// 已经有一个权限了,直接修改权限
			bAdmin.setRoleId(roleId);
			this.updateById(bAdmin);
			return true;
		}else {
			// 获取需要授权的用户信息
			BUser bUser = bUserMapper.selectById(userId);
			BAdmin admin = new BAdmin();
			admin.setUsername(bUser.getUsername());
			admin.setPassword(bUser.getPassword());
			admin.setAvtar(bUser.getAvatar());
			admin.setNickname(bUser.getNickname());
			admin.setRoleId(roleId);

			this.save(admin);
			return true;
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean cancelAuthorization(Integer userId) {
		boolean b = this.removeById(userId);
		return b;
	}
}




